#include "game.h"
#include "game_render_group.h"
#include "game_sort.h"
platform_api Platform;

#if 1
#include "../iaca-win64/iacaMarks.h"
#else
#define IACA_VC64_START
#define IACA_VC64_END
#endif

#define mmSquare(a) _mm_mul_ps(a, a)
#define M(a, i) ((float *)&(a))[i]
#define Mi(a, i) ((uint32 *)&(a))[i]
// 渲染一个矩形区域
internal void DrawRectangle(loaded_bitmap *Buffer, v2 vMin, v2 vMax, v4 Color,
                            rectangle2i ClipRect) {
    rectangle2i FillRect;
    // 将传入的浮动点数坐标四舍五入为整数坐标
    FillRect.MinX = RoundReal32ToInt32(vMin.x);  // 四舍五入并转换为整数
    FillRect.MinY = RoundReal32ToInt32(vMin.y);  // 四舍五入并转换为整数
    FillRect.MaxX = RoundReal32ToInt32(vMax.x);  // 四舍五入并转换为整数
    FillRect.MaxY = RoundReal32ToInt32(vMax.y);  // 四舍五入并转换为整数

    FillRect = Intersect(ClipRect, FillRect);
#if 0
    real32 R = Color.r;
    real32 G = Color.g;
    real32 B = Color.b;
    real32 A = Color.a;
    // 将浮动的颜色值 (R, G, B) 转换为 32 位颜色值格式: 0x AA RR GG BB
    // 其中 R、G、B 都是浮动的值，在0到1之间，最终转换为0到255的整数

    uint32 Color32 =
        (uint32)((RoundReal32ToInt32(A * 255.0f) << 24) |
                 (RoundReal32ToUInt32(R * 255.0f)
                  << 16) |  // 将 R 颜色值乘以255并四舍五入，然后左移16位，放到高8位（RR部分）
                 (RoundReal32ToUInt32(G * 255.0f)
                  << 8) |  // 将 G 颜色值乘以255并四舍五入，然后左移8位，放到中间8位（GG部分）
                 (RoundReal32ToUInt32(B * 255.0f)
                  << 0));  // 将 B 颜色值乘以255并四舍五入，放到低8位（BB部分）
    // 计算矩形起始的内存地址（Row是当前行的起始地址）
    uint8 *Row = (uint8 *)Buffer->Memory + FillRect.MinX * BITMAP_BYTES_PER_PIEXLE +
                 FillRect.MinY * Buffer->Pitch;
    // 遍历矩形区域的每一行（从MinY到MaxY）
    for (int Y = FillRect.MinY; Y < FillRect.MaxY; ++Y) {
        // 当前行的起始地址，Pixel是指向当前行的像素数据指针
        uint32 *Pixel = (uint32 *)Row;

        // 遍历当前行的每一个像素（从MinX到MaxX）
        for (int X = FillRect.MinX; X < FillRect.MaxX; ++X) {
            // 将当前像素的颜色设置为白色
            *(uint32 *)Pixel++ = Color32;  // 将颜色赋给当前像素并移动指针
        }
        // 跳到下一行的起始地址
        Row += Buffer->Pitch;  // 根据图像的每行的字节数跳到下一行
    }
#else
    Color *= 255.0f;
    Color.rgb *= 255.0f;
    if (HasArea(FillRect)) {
        __m128i StartClipMask = _mm_set1_epi8(-1);
        __m128i EndClipMask = _mm_set1_epi8(-1);

        __m128i StartClipMasks[] = {
            _mm_slli_si128(StartClipMask, 0 * 4),
            _mm_slli_si128(StartClipMask, 1 * 4),
            _mm_slli_si128(StartClipMask, 2 * 4),
            _mm_slli_si128(StartClipMask, 3 * 4),
        };

        __m128i EndClipMasks[] = {
            _mm_srli_si128(EndClipMask, 0 * 4),
            _mm_srli_si128(EndClipMask, 3 * 4),
            _mm_srli_si128(EndClipMask, 2 * 4),
            _mm_srli_si128(EndClipMask, 1 * 4),
        };

        if (FillRect.MinX & 3) {
            StartClipMask = StartClipMasks[FillRect.MinX & 3];
            FillRect.MinX = FillRect.MinX & ~3;
        }

        if (FillRect.MaxX & 3) {
            EndClipMask = EndClipMasks[FillRect.MaxX & 3];
            FillRect.MaxX = (FillRect.MaxX & ~3) + 4;
        }

        real32 Inv255 = 1.0f / 255.0f;
        __m128 Inv255_4x = _mm_set1_ps(Inv255);

        __m128 One = _mm_set1_ps(1.0f);
        __m128 Zero = _mm_set1_ps(0.0f);
        __m128i MaskFF = _mm_set1_epi32(0xFF);
        __m128 Colorr_4x = _mm_set1_ps(Color.r);
        __m128 Colorg_4x = _mm_set1_ps(Color.g);
        __m128 Colorb_4x = _mm_set1_ps(Color.b);
        __m128 Colora_4x = _mm_set1_ps(Color.a);
        __m128 MaxColorValue = _mm_set1_ps(255.0f * 255.0f);

        uint8 *Row = ((uint8 *)Buffer->Memory + FillRect.MinX * BITMAP_BYTES_PER_PIEXLE +
                      FillRect.MinY * Buffer->Pitch);
        int32 RowAdvance = Buffer->Pitch;

        int MinY = FillRect.MinY;
        int MaxY = FillRect.MaxY;
        int MinX = FillRect.MinX;
        int MaxX = FillRect.MaxX;

        // TIMED_BLOCK("Pixel Fill", GetClampedRectArea(FillRect) / 2);
        for (int Y = MinY; Y < MaxY; ++Y) {
            __m128i ClipMask = StartClipMask;

            uint32 *Pixel = (uint32 *)Row;
            for (int XI = MinX; XI < MaxX; XI += 4) {
                IACA_VC64_START;
                __m128i WriteMask = ClipMask;

                {
                    __m128i OriginalDest = _mm_load_si128((__m128i *)Pixel);

                    __m128 Destb = _mm_cvtepi32_ps(_mm_and_si128(OriginalDest, MaskFF));
                    __m128 Destg =
                        _mm_cvtepi32_ps(_mm_and_si128(_mm_srli_epi32(OriginalDest, 8), MaskFF));
                    __m128 Destr =
                        _mm_cvtepi32_ps(_mm_and_si128(_mm_srli_epi32(OriginalDest, 16), MaskFF));
                    __m128 Desta =
                        _mm_cvtepi32_ps(_mm_and_si128(_mm_srli_epi32(OriginalDest, 24), MaskFF));

                    __m128 Texelr = Colorr_4x;
                    __m128 Texelg = Colorg_4x;
                    __m128 Texelb = Colorb_4x;
                    __m128 Texela = Colora_4x;

                    Texelr = _mm_min_ps(_mm_max_ps(Texelr, Zero), MaxColorValue);
                    Texelg = _mm_min_ps(_mm_max_ps(Texelg, Zero), MaxColorValue);
                    Texelb = _mm_min_ps(_mm_max_ps(Texelb, Zero), MaxColorValue);

                    Destr = mmSquare(Destr);
                    Destg = mmSquare(Destg);
                    Destb = mmSquare(Destb);

                    __m128 InvTexelA = _mm_sub_ps(One, _mm_mul_ps(Inv255_4x, Texela));
                    __m128 Blendedr = _mm_add_ps(_mm_mul_ps(InvTexelA, Destr), Texelr);
                    __m128 Blendedg = _mm_add_ps(_mm_mul_ps(InvTexelA, Destg), Texelg);
                    __m128 Blendedb = _mm_add_ps(_mm_mul_ps(InvTexelA, Destb), Texelb);
                    __m128 Blendeda = _mm_add_ps(_mm_mul_ps(InvTexelA, Desta), Texela);

#if 1
                    Blendedr = _mm_mul_ps(Blendedr, _mm_rsqrt_ps(Blendedr));
                    Blendedg = _mm_mul_ps(Blendedg, _mm_rsqrt_ps(Blendedg));
                    Blendedb = _mm_mul_ps(Blendedb, _mm_rsqrt_ps(Blendedb));
#else
                    Blendedr = _mm_sqrt_ps(Blendedr);
                    Blendedg = _mm_sqrt_ps(Blendedg);
                    Blendedb = _mm_sqrt_ps(Blendedb);
#endif

                    __m128i Intr = _mm_cvtps_epi32(Blendedr);
                    __m128i Intg = _mm_cvtps_epi32(Blendedg);
                    __m128i Intb = _mm_cvtps_epi32(Blendedb);
                    __m128i Inta = _mm_cvtps_epi32(Blendeda);

                    __m128i Sr = _mm_slli_epi32(Intr, 16);
                    __m128i Sg = _mm_slli_epi32(Intg, 8);
                    __m128i Sb = Intb;
                    __m128i Sa = _mm_slli_epi32(Inta, 24);

                    __m128i Out = _mm_or_si128(_mm_or_si128(Sr, Sg), _mm_or_si128(Sb, Sa));

                    __m128i MaskedOut = _mm_or_si128(_mm_and_si128(WriteMask, Out),
                                                     _mm_andnot_si128(WriteMask, OriginalDest));
                    _mm_store_si128((__m128i *)Pixel, MaskedOut);
                }

                Pixel += 4;

                if ((XI + 8) < MaxX) {
                    ClipMask = _mm_set1_epi8(-1);
                } else {
                    ClipMask = EndClipMask;
                }

                IACA_VC64_END;
            }

            Row += RowAdvance;
        }
    }
#endif
}

// ChangeSaturation 根据指定的饱和度级别（Level）修改给定位图缓冲区的饱和度。
// 该函数处理缓冲区中的每个像素，调整其饱和度，并相应地更新像素颜色。

internal void ChangeSaturation(loaded_bitmap *Buffer, real32 Level) {
    // TIMED_FUNCTION();
    // 获取指向位图内存的第一行的指针
    uint8 *DestRow = (uint8 *)Buffer->Memory;

    // 遍历缓冲区中的每一行
    for (int Y = 0; Y < Buffer->Height; Y++) {
        uint32 *Dest = (uint32 *)DestRow;
        // 指向当前行像素的指针

        // 遍历当前行中的每个像素
        for (int X = 0; X < Buffer->Width; X++) {
            // 从像素中提取单独的颜色组件（R、G、B、A）
            v4 D = {(real32)((*Dest >> 16) & 0xFF),   // 红色分量（R）
                    (real32)((*Dest >> 8) & 0xFF),    // 绿色分量（G）
                    (real32)((*Dest >> 0) & 0xFF),    // 蓝色分量（B）
                    (real32)((*Dest >> 24) & 0xFF)};  // alpha（透明度）分量（A）

            // 将颜色从SRGB空间转换为线性颜色空间，以便进行精确的饱和度调整
            D = SRGB255ToLinear1(D);

            // 计算RGB通道的平均值（作为饱和度调整的基准）
            real32 Avg = (1.0f / 3.0f) * (D.r + D.g + D.b);

            // 计算每个RGB通道的增量（该通道值与平均值之间的差异）
            v3 Delta = v3{D.r - Avg, D.g - Avg, D.b - Avg};

            // 通过调整增量的饱和度来改变饱和度，然后将其与平均值组合以形成新的颜色
            v4 Result = ToV4({v3{Avg, Avg, Avg} + Level * Delta}, D.a);

            // 将颜色从线性空间转换回SRGB空间以便显示
            Result = Linear1ToSRGB255(Result);

            // 更新像素值，保持alpha（透明度）不变
            *Dest = (((uint32)(Result.a + 0.5f) << 24) |  // alpha通道
                     ((uint32)(Result.r + 0.5f) << 16) |  // 红色通道
                     ((uint32)(Result.g + 0.5f) << 8) |   // 绿色通道
                     ((uint32)(Result.b + 0.5f) << 0)     // 蓝色通道
            );
            Dest++;
        }

        // 移动到缓冲区中的下一行
        DestRow += Buffer->Pitch;
    }
}

internal void BlendRenderTarget(rectangle2i Rect, loaded_bitmap *DestTarget, real32 Alpha,
                                loaded_bitmap *SourceTarget) {
#if 0
    uint8 *DestRow = (uint8 *)DestTarget->Memory + Rect.MinX * BITMAP_BYTES_PER_PIEXLE +
                     Rect.MinY * DestTarget->Pitch;
    uint8 *SourceRow = (uint8 *)SourceTarget->Memory + Rect.MinX * BITMAP_BYTES_PER_PIEXLE +
                       Rect.MinY * SourceTarget->Pitch;
    for (int32 Y = Rect.MinY; Y < Rect.MaxY; ++Y) {
        uint32 *DestPixel = (uint32 *)DestRow;
        uint32 *SourcePixel = (uint32 *)SourceRow;

        for (int32 X = Rect.MinX; X < Rect.MaxX; ++X) {
            v4 SourceColor = SRGB255ToLinear1(Unpack4x8(*SourcePixel));
            v4 DestColor = SRGB255ToLinear1(Unpack4x8(*DestPixel));
            real32 PixelAlpha = Alpha*SourceColor.a;
            v4 Result = (1.0f - PixelAlpha) * DestColor + PixelAlpha * SourceColor;

            *DestPixel = Pack4x8(Linear1ToSRGB255(Result));
            ++DestPixel;
            ++SourcePixel;
        }
        DestRow += DestTarget->Pitch;
        SourceRow += SourceTarget->Pitch;
    }
#else
    if (HasArea(Rect)) {
        __m128i StartClipMask = _mm_set1_epi8(-1);
        __m128i EndClipMask = _mm_set1_epi8(-1);

        __m128i StartClipMasks[] = {
            _mm_slli_si128(StartClipMask, 0 * 4),
            _mm_slli_si128(StartClipMask, 1 * 4),
            _mm_slli_si128(StartClipMask, 2 * 4),
            _mm_slli_si128(StartClipMask, 3 * 4),
        };

        __m128i EndClipMasks[] = {
            _mm_srli_si128(EndClipMask, 0 * 4),
            _mm_srli_si128(EndClipMask, 3 * 4),
            _mm_srli_si128(EndClipMask, 2 * 4),
            _mm_srli_si128(EndClipMask, 1 * 4),
        };

        if (Rect.MinX & 3) {
            StartClipMask = StartClipMasks[Rect.MinX & 3];
            Rect.MinX = Rect.MinX & ~3;
        }

        if (Rect.MaxX & 3) {
            EndClipMask = EndClipMasks[Rect.MaxX & 3];
            Rect.MaxX = (Rect.MaxX & ~3) + 4;
        }

        __m128i MaskFF = _mm_set1_epi32(0xFF);
        __m128 Alpha_4x = _mm_set1_ps(Alpha);
        real32 Inv255 = 1.0f / 255.0f;
        __m128 Inv255_4x = _mm_set1_ps(Inv255);

        __m128 One = _mm_set1_ps(1.0f);

        uint8 *DestRow = (uint8 *)DestTarget->Memory + Rect.MinX * BITMAP_BYTES_PER_PIEXLE +
                         Rect.MinY * DestTarget->Pitch;
        uint8 *SourceRow = (uint8 *)SourceTarget->Memory + Rect.MinX * BITMAP_BYTES_PER_PIEXLE +
                           Rect.MinY * SourceTarget->Pitch;
        int32 DestRowAdvance = DestTarget->Pitch;
        int32 SourceRowAdvance = SourceTarget->Pitch;

        int MinY = Rect.MinY;
        int MaxY = Rect.MaxY;
        int MinX = Rect.MinX;
        int MaxX = Rect.MaxX;

        // TIMED_BLOCK("Pixel Fill", GetClampedRectArea(FillRect) / 2);
        for (int Y = MinY; Y < MaxY; ++Y) {
            __m128i ClipMask = StartClipMask;

            uint32 *DestPixel = (uint32 *)DestRow;
            uint32 *SourcePixel = (uint32 *)SourceRow;

            for (int XI = MinX; XI < MaxX; XI += 4) {
                IACA_VC64_START;
                __m128i WriteMask = ClipMask;

                {
                    __m128i OriginalDest = _mm_load_si128((__m128i *)DestPixel);
                    __m128i OriginalSource = _mm_load_si128((__m128i *)SourcePixel);

                    __m128 Destb = _mm_cvtepi32_ps(_mm_and_si128(OriginalDest, MaskFF));
                    __m128 Destg =
                        _mm_cvtepi32_ps(_mm_and_si128(_mm_srli_epi32(OriginalDest, 8), MaskFF));
                    __m128 Destr =
                        _mm_cvtepi32_ps(_mm_and_si128(_mm_srli_epi32(OriginalDest, 16), MaskFF));
                    __m128 Desta =
                        _mm_cvtepi32_ps(_mm_and_si128(_mm_srli_epi32(OriginalDest, 24), MaskFF));

                    __m128 Sourceb = _mm_cvtepi32_ps(_mm_and_si128(OriginalSource, MaskFF));
                    __m128 Sourceg =
                        _mm_cvtepi32_ps(_mm_and_si128(_mm_srli_epi32(OriginalSource, 8), MaskFF));
                    __m128 Sourcer =
                        _mm_cvtepi32_ps(_mm_and_si128(_mm_srli_epi32(OriginalSource, 16), MaskFF));
                    __m128 Sourcea =
                        _mm_cvtepi32_ps(_mm_and_si128(_mm_srli_epi32(OriginalSource, 24), MaskFF));

                    Destr = mmSquare(Destr);
                    Destg = mmSquare(Destg);
                    Destb = mmSquare(Destb);
                    Sourcer = mmSquare(Sourcer);
                    Sourceg = mmSquare(Sourceg);
                    Sourceb = mmSquare(Sourceb);
                    __m128 PixelAlpha_4x = _mm_mul_ps(Alpha_4x, _mm_mul_ps(Inv255_4x, Sourcea));
                    __m128 InvPixelAlpha_4x = _mm_sub_ps(One, PixelAlpha_4x);
                    __m128 Blendedr = _mm_add_ps(_mm_mul_ps(InvPixelAlpha_4x, Destr),
                                                 _mm_mul_ps(InvPixelAlpha_4x, Sourcer));
                    __m128 Blendedg = _mm_add_ps(_mm_mul_ps(InvPixelAlpha_4x, Destg),
                                                 _mm_mul_ps(InvPixelAlpha_4x, Sourceg));
                    __m128 Blendedb = _mm_add_ps(_mm_mul_ps(InvPixelAlpha_4x, Destb),
                                                 _mm_mul_ps(InvPixelAlpha_4x, Sourceb));
                    __m128 Blendeda = _mm_add_ps(_mm_mul_ps(InvPixelAlpha_4x, Desta),
                                                 _mm_mul_ps(InvPixelAlpha_4x, Sourcea));

#if 1
                    Blendedr = _mm_mul_ps(Blendedr, _mm_rsqrt_ps(Blendedr));
                    Blendedg = _mm_mul_ps(Blendedg, _mm_rsqrt_ps(Blendedg));
                    Blendedb = _mm_mul_ps(Blendedb, _mm_rsqrt_ps(Blendedb));
#else
                    Blendedr = _mm_sqrt_ps(Blendedr);
                    Blendedg = _mm_sqrt_ps(Blendedg);
                    Blendedb = _mm_sqrt_ps(Blendedb);
#endif

                    __m128i Intr = _mm_cvtps_epi32(Blendedr);
                    __m128i Intg = _mm_cvtps_epi32(Blendedg);
                    __m128i Intb = _mm_cvtps_epi32(Blendedb);
                    __m128i Inta = _mm_cvtps_epi32(Blendeda);

                    __m128i Sr = _mm_slli_epi32(Intr, 16);
                    __m128i Sg = _mm_slli_epi32(Intg, 8);
                    __m128i Sb = Intb;
                    __m128i Sa = _mm_slli_epi32(Inta, 24);

                    __m128i Out = _mm_or_si128(_mm_or_si128(Sr, Sg), _mm_or_si128(Sb, Sa));

                    __m128i MaskedOut = _mm_or_si128(_mm_and_si128(WriteMask, Out),
                                                     _mm_andnot_si128(WriteMask, OriginalDest));
                    _mm_store_si128((__m128i *)DestPixel, MaskedOut);
                }

                SourcePixel += 4;
                DestPixel += 4;
                if ((XI + 8) < MaxX) {
                    ClipMask = _mm_set1_epi8(-1);
                } else {
                    ClipMask = EndClipMask;
                }

                IACA_VC64_END;
            }

            DestRow += DestRowAdvance;
            SourceRow += SourceRowAdvance;
        }
    }
#endif
}

internal void ClearRectangle(rectangle2i Rect, loaded_bitmap *DestTarget, v4 Color) {
    if (HasArea(Rect)) {
        __m128i StartClipMask = _mm_set1_epi8(-1);
        __m128i EndClipMask = _mm_set1_epi8(-1);

        __m128i StartClipMasks[] = {
            _mm_slli_si128(StartClipMask, 0 * 4),
            _mm_slli_si128(StartClipMask, 1 * 4),
            _mm_slli_si128(StartClipMask, 2 * 4),
            _mm_slli_si128(StartClipMask, 3 * 4),
        };

        __m128i EndClipMasks[] = {
            _mm_srli_si128(EndClipMask, 0 * 4),
            _mm_srli_si128(EndClipMask, 3 * 4),
            _mm_srli_si128(EndClipMask, 2 * 4),
            _mm_srli_si128(EndClipMask, 1 * 4),
        };

        if (Rect.MinX & 3) {
            StartClipMask = StartClipMasks[Rect.MinX & 3];
            Rect.MinX = Rect.MinX & ~3;
        }

        if (Rect.MaxX & 3) {
            EndClipMask = EndClipMasks[Rect.MaxX & 3];
            Rect.MaxX = (Rect.MaxX & ~3) + 4;
        }

        uint8 *DestRow = (uint8 *)DestTarget->Memory + Rect.MinX * BITMAP_BYTES_PER_PIEXLE +
                         Rect.MinY * DestTarget->Pitch;
        int32 DestRowAdvance = DestTarget->Pitch;

        int MinY = Rect.MinY;
        int MaxY = Rect.MaxY;
        int MinX = Rect.MinX;
        int MaxX = Rect.MaxX;
        __m128 Colorr = _mm_set1_ps(255.0f * 255.0f * Color.r);
        __m128 Colorg = _mm_set1_ps(255.0f * 255.0f * Color.g);
        __m128 Colorb = _mm_set1_ps(255.0f * 255.0f * Color.b);
        __m128 Colora = _mm_set1_ps(255.0f * 255.0f * Color.a);

        __m128 Blendedr = _mm_mul_ps(Colorr, _mm_rsqrt_ps(Colorr));
        __m128 Blendedg = _mm_mul_ps(Colorg, _mm_rsqrt_ps(Colorg));
        __m128 Blendedb = _mm_mul_ps(Colorb, _mm_rsqrt_ps(Colorb));
        __m128 Blendeda = Colora;

        __m128i Intr = _mm_cvtps_epi32(Blendedr);
        __m128i Intg = _mm_cvtps_epi32(Blendedg);
        __m128i Intb = _mm_cvtps_epi32(Blendedb);
        __m128i Inta = _mm_cvtps_epi32(Blendeda);

        __m128i Sr = _mm_slli_epi32(Intr, 16);
        __m128i Sg = _mm_slli_epi32(Intg, 8);
        __m128i Sb = Intb;
        __m128i Sa = _mm_slli_epi32(Inta, 24);
        __m128i Out = _mm_or_si128(_mm_or_si128(Sr, Sg), _mm_or_si128(Sb, Sa));

        for (int Y = MinY; Y < MaxY; ++Y) {
            __m128i ClipMask = StartClipMask;

            uint32 *DestPixel = (uint32 *)DestRow;

            for (int XI = MinX; XI < MaxX; XI += 4) {
                IACA_VC64_START;
                __m128i WriteMask = ClipMask;
                __m128i OriginalDest = _mm_or_si128(_mm_or_si128(Sr, Sg), _mm_or_si128(Sb, Sa));

                __m128i MaskedOut = _mm_or_si128(_mm_and_si128(WriteMask, Out),
                                                 _mm_andnot_si128(WriteMask, OriginalDest));

                _mm_store_si128((__m128i *)DestPixel, MaskedOut);

                DestPixel += 4;
                if ((XI + 8) < MaxX) {
                    ClipMask = _mm_set1_epi8(-1);
                } else {
                    ClipMask = EndClipMask;
                }

                IACA_VC64_END;
            }

            DestRow += DestRowAdvance;
        }
    }
}

void RenderCommandsToBitmap(game_render_commands *Commands, game_render_prep *Prep,
                            loaded_bitmap *RenderTargets, rectangle2i BaseClipRect) {
    TIMED_FUNCTION();

    real32 NullPixelIsToMeters = 1.0f;
    uint32 ClipRectIndex = 0xFFFFFFFF;
    rectangle2i ClipRect = BaseClipRect;
    for (uint32 TargetIndex = 0; TargetIndex <= Commands->MaxRenderTargetIndex; ++TargetIndex) {
        loaded_bitmap *OutputTarget = RenderTargets + TargetIndex;
        ClearRectangle(ClipRect, OutputTarget, Commands->ClearColor);
    }
    loaded_bitmap *OutputTarget = RenderTargets;
    uint32 *Enty = Prep->SortedIndices;
    for (uint32 SortEntryIndex = 0; SortEntryIndex < Prep->SortedIndexCount;
         ++SortEntryIndex, ++Enty) {
        uint32 HeadOffset = *Enty;
        // 获取当前渲染条目的头部信息
        render_group_entry_header *Header =
            (render_group_entry_header *)(Commands->PushBufferBase + HeadOffset);
        if (ClipRectIndex != Header->ClipRectIndex) {
            ClipRectIndex = Header->ClipRectIndex;
            Assert(ClipRectIndex < Commands->ClipRectCount);
            render_entry_cliprect *Clip = Prep->ClipRects + ClipRectIndex;
            ClipRect = Intersect(BaseClipRect, Clip->Rect);
            OutputTarget = RenderTargets + Clip->RenderTargetIndex;
        }

        void *Data = (uint8 *)Header + sizeof(*Header);

        // 根据条目的类型进行不同的处理
        switch (Header->Type) {
            // 处理渲染组条目类型为饱和度调整的情况
            case RenderGroupEntryType_render_entry_saturation: {
                // 将数据指针转换为饱和度渲染条目类型
                render_entry_saturation *Entry = (render_entry_saturation *)Data;

                // 调用 ChangeSaturation 函数来调整输出目标的饱和度
                ChangeSaturation(OutputTarget, Entry->Level);
            }

            case RenderGroupEntryType_render_entry_bitmap: {
                // 处理位图渲染条目
                render_entry_bitmap *Entry = (render_entry_bitmap *)Data;

                Assert(Entry->Bitmap);
// 在 OutputTarget 上绘制 Bitmap，使用给定的透明度 (A)
#if 0

// DrawBitMap(OutputTarget, Entry->Bitmap, P.x, P.y, Entry->Color.a);
DrawRectangleSlowly(OutputTarget, P,                        //
            Basis.SCale * v2{Entry->Size.x, 0.0f},  //
            Basis.SCale * v2{0.0f, Entry->Size.y},  //
            Entry->Color,                           //
            Entry->Bitmap,                          //
            0, 0, 0, 0,                             //
            RenderGroup->MetersToPixels);
#else
// DrawBitMap(OutputTarget, Entry->Bitmap, P.x, P.y, Entry->Color.a);
#if 0
thread_local static std::atomic<real32> Angle = 1.0f;
Angle += 0.0000001f;
v2 XAxis = {Cos(Angle), Sin(Angle)};

#endif

                DrawRectangleQuickly(OutputTarget, Entry->P,  //
                                     Entry->XAxis,            //
                                     Entry->YAxis,            //
                                     Entry->PremulColor,      //
                                     Entry->Bitmap,           //
                                     NullPixelIsToMeters, ClipRect);
#endif
            } break;

            case RenderGroupEntryType_render_entry_rectangle: {
                // 处理矩形渲染条目
                render_entry_rectangle *Entry = (render_entry_rectangle *)Data;

                // 在 OutputTarget 上绘制矩形，使用给定的颜色 (R, G, B)
                DrawRectangle(OutputTarget, Entry->P, Entry->P + Entry->Dim, Entry->PremulColor,
                              ClipRect);
            } break;

            case RenderGroupEntryType_render_entry_coordinate_system: {
                // 处理坐标系渲染条目
                render_entry_coordinate_system *Entry = (render_entry_coordinate_system *)Data;
                v4 Color = Entry->Color;  // 获取颜色
                v2 Dim = {5, 5};          // 坐标轴标记的大小
                v2 vMax = Entry->Origin + Entry->XAxis + Entry->YAxis;
                v2 P = Entry->Origin;
                (void)Color;
                (void)Dim;
                (void)vMax;
                (void)P;
#if 0
// 绘制坐标系的四个方向
DrawRectangle(OutputTarget, P - Dim, P + Dim, Color);
// 绘制原点标记

P = Entry->Origin + Entry->XAxis;
DrawRectangle(OutputTarget, P - Dim, P + Dim, Color);
// 绘制 X 轴标记

P = Entry->Origin + Entry->YAxis;
DrawRectangle(OutputTarget, P - Dim, P + Dim, Color);
// 绘制 Y 轴标记

P = Entry->Origin + Entry->XAxis + Entry->YAxis;
DrawRectangle(OutputTarget, P - Dim, P + Dim, Color);
// 绘制 Z 轴标记

// 绘制坐标系的详细元素，包括纹理和环境贴图等
DrawRectangleSlowly(OutputTarget,   //
            Entry->Origin,  //
            Entry->XAxis,   //
            Entry->YAxis,
            Entry->Color,      //
            Entry->Texture,    //
            Entry->NormalMap,  //
            Entry->Top,        //
            Entry->Middle,     //
            Entry->Bottom,     //
            RenderGroup->MetersToPixels);
#if 0
// 如果有多个位置点需要渲染，可以在这里处理
for (uint32 PIndex = 0; PIndex < ArrayCount(Entry->Posints); ++PIndex) {
P = Entry->Posints[PIndex];
P = Entry->Origin + P.x * Entry->XAxis + P.y * Entry->YAxis;
// 绘制其他位置点的标记
DrawRectangle(OutputTarget, P - Dim, P + Dim, Entry->Color.r, Entry->Color.g,
            Entry->Color.b);  
}
#endif
#endif
            } break;
            case RenderGroupEntryType_render_entry_blend_render_target: {
                render_entry_blend_render_target *Entry = (render_entry_blend_render_target *)Data;
                loaded_bitmap *SourceTarget = RenderTargets + Entry->SourceTargetIndex;
                BlendRenderTarget(ClipRect, OutputTarget, Entry->Alpha, SourceTarget);
            } break;
                InvalidDefaultCase;
        }
    }
}

internal PLATFORM_WORK_QUEUE_CALLBACK(DoTiledRenderWork) {  //
    (void)Queue;
    TIMED_FUNCTION();
    tile_render_work *Work = (tile_render_work *)Data;
    RenderCommandsToBitmap(Work->Commands, Work->Prep, Work->RenderTargets, Work->ClipRect);
    // RenderGroupToOutput(Work->RenderGroup, Work->OutputTarget, Work->ClipRect, false);
}
void SoftwareRenderCommands(platform_work_queue *RenderQueue, game_render_commands *Commands,
                            game_render_prep *Prep, loaded_bitmap *FinalOutputTarget,
                            memory_arena *TempArena) {
    TIMED_FUNCTION();
    (void)Prep;
    (void)TempArena;
    // 根据最大渲染目标索引计算实际需要的渲染目标数量（+1 是因为索引从 0 开始）
    uint32 RenderTargetCount = Commands->MaxRenderTargetIndex + 1;

    // 在临时内存池中为所有渲染目标分配一段数组空间，每个元素是一个 loaded_bitmap
    loaded_bitmap *RenderTargets = PushArray(TempArena, RenderTargetCount, loaded_bitmap);

    // 确保最终输出缓冲（屏幕缓冲）的行跨度（Pitch）是合法的
    Assert(FinalOutputTarget->Pitch > 0);

    // 将最终输出缓冲作为第 0 号渲染目标（RenderTargets[0]），用于直接显示到屏幕
    RenderTargets[0] = *FinalOutputTarget;

    // 从索引 1 开始，为其余的渲染目标依次创建缓冲区
    for (uint32 TargetIndex = 1; TargetIndex < RenderTargetCount; ++TargetIndex) {
        // 取得当前渲染目标指针
        loaded_bitmap *Target = RenderTargets + TargetIndex;

        // 拷贝最终输出缓冲的结构信息（尺寸、像素格式、Pitch 等保持一致）
        *Target = *FinalOutputTarget;

        // 为当前渲染目标分配独立的像素存储内存，大小 = Pitch * Height
        // 使用 16 字节对齐（AlignNoClear(16)），保证内存对齐优化
        Target->Memory = PushSize(TempArena, Target->Pitch * Target->Height, AlignNoClear(16));
    }

    const int TileCountX = 9;
    const int TileCountY = 9;
    tile_render_work WorkArray[TileCountX * TileCountY];
#if 1
    Assert(((uintptr)FinalOutputTarget->Memory & 15) == 0);
#endif
    int WorkCount = 0;
    int TileWidth = FinalOutputTarget->Width / TileCountX;
    int TileHeight = FinalOutputTarget->Height / TileCountY;
    TileWidth = ((TileWidth + 3) / 4) * 4;

    for (int TileY = 0; TileY < TileCountY; ++TileY) {
        for (int TileX = 0; TileX < TileCountX; ++TileX) {
            tile_render_work *Work = WorkArray + WorkCount++;
            rectangle2i ClipRect;
            ClipRect.MinX = TileX * TileWidth;
            ClipRect.MaxX = ClipRect.MinX + TileWidth;
            ClipRect.MinY = TileY * TileHeight;
            ClipRect.MaxY = ClipRect.MinY + TileHeight;
            if (TileX == (TileCountX - 1)) {
                ClipRect.MaxX = FinalOutputTarget->Width;
            }
            if (TileY == (TileCountY - 1)) {
                ClipRect.MaxY = FinalOutputTarget->Height;
            }
            Work->Commands = Commands;
            Work->RenderTargets = RenderTargets;
            Work->ClipRect = ClipRect;
            Work->Prep = Prep;
            // Work->SortSpace =
            //     PushArray(TempArena, RenderGroup->PushBufferElementCount, tile_sort_entry);

            Platform.AddEntry(RenderQueue, DoTiledRenderWork, Work);
        }
    }
    Platform.CompleteAllWork(RenderQueue);
    (void)RenderQueue;
}

// 渲染一个矩形区域
void DrawRectangleQuickly(loaded_bitmap *Buffer, v2 Origin, v2 XAxis, v2 YAxis, v4 Color,
                          loaded_bitmap *Texture,  //
                          real32 PixelsToMeters, rectangle2i ClipRect) {
#define COUNT_CYCLES 0
    (void)PixelsToMeters;
    uint32 Color32 =
        (uint32)((RoundReal32ToInt32(Color.a * 255.0f) << 24) |
                 (RoundReal32ToUInt32(Color.r * 255.0f)
                  << 16) |  // 将 R 颜色值乘以255并四舍五入，然后左移16位，放到高8位（RR部分）
                 (RoundReal32ToUInt32(Color.g * 255.0f)
                  << 8) |  // 将 G 颜色值乘以255并四舍五入，然后左移8位，放到中间8位（GG部分）
                 (RoundReal32ToUInt32(Color.b * 255.0f)
                  << 0));  // 将 B 颜色值乘以255并四舍五入，放到低8位（BB部分）
    (void)Color32;
    // 获取缓冲区的最大宽度和最大高度
    int WidthMax = Buffer->Width - 3;
    int HeightMax = Buffer->Height - 3;

    // 初始化最小和最大值，分别用于 X 和 Y 轴
    int XMin = WidthMax;
    int XMax = 0;
    int YMin = HeightMax;
    int YMax = 0;

    // 定义四个测试点，表示矩形的四个角
    v2 P[4] = {Origin, Origin + XAxis, Origin + XAxis + YAxis, Origin + YAxis};
    rectangle2i FillRect = InvertedInfinityRectangle2i();  // {WidthMax, HeightMax, 0, 0};

    // 遍历四个点，计算其对应的Floor值和Fei值
    for (uint32 PIndex = 0; PIndex < ArrayCount(P); PIndex++) {
        v2 TestP = P[PIndex];

        // 获取当前点的地板值和天花板值，分别用于 X 和 Y 轴
        int FloorX = FloorReal32ToInt32(TestP.x);
        int CeilX = CeilReal32ToInt32(TestP.x) + 1;
        int FloorY = FloorReal32ToInt32(TestP.y);
        int CeilY = CeilReal32ToInt32(TestP.y) + 1;

        // 更新 XMin 和 XMax，确保 XMin 是所有点的最小 X 值，XMax 是最大 X 值
        if (FillRect.MinX > FloorX) {
            FillRect.MinX = FloorX;
        }
        if (FillRect.MaxX < CeilX) {
            FillRect.MaxX = CeilX;
        }

        // 更新 YMin 和 YMax，确保 YMin 是所有点的最小 Y 值，YMax 是最大 Y 值
        if (FillRect.MinY > FloorY) {
            FillRect.MinY = FloorY;
        }
        if (FillRect.MaxY < CeilY) {
            FillRect.MaxY = CeilY;
        }
    }
#if 0
    rectangle2i ClipRect = {0, 1, WidthMax, HeightMax};
#else
    // rectangle2i ClipRect = {128, 128, 256, 256};
#endif
    FillRect = Intersect(ClipRect, FillRect);

    if (HasArea(FillRect)) {
        __m128i StartClipMask = _mm_set1_epi8(-1);
        __m128i EndClipMask = _mm_set1_epi8(-1);
        __m128i StartClipMasks[] = {
            _mm_slli_si128(StartClipMask, 0 * 4),
            _mm_slli_si128(StartClipMask, 1 * 4),
            _mm_slli_si128(StartClipMask, 2 * 4),
            _mm_slli_si128(StartClipMask, 3 * 4),
        };
        __m128i EndClipMasks[] = {
            _mm_srli_si128(EndClipMask, 0 * 4),
            _mm_srli_si128(EndClipMask, 3 * 4),
            _mm_srli_si128(EndClipMask, 2 * 4),
            _mm_srli_si128(EndClipMask, 1 * 4),
        };

        if (FillRect.MinX & 3) {
            StartClipMask = StartClipMasks[FillRect.MinX & 3];
            FillRect.MinX = FillRect.MinX & ~3;
        }
        if (FillRect.MaxX & 3) {
            EndClipMask = EndClipMasks[FillRect.MaxX & 3];
            FillRect.MaxX = (FillRect.MaxX & ~3) + 4;
        }

        XMin = FillRect.MinX;
        XMax = FillRect.MaxX;
        YMin = FillRect.MinY;
        YMax = FillRect.MaxY;
        real32 Det = XAxis.x * YAxis.y - XAxis.y * YAxis.x;
        if (Det == 0.0f) {
            Det = 1.0f;
        }
        v2 nXAxis = {YAxis.y / Det, -YAxis.x / Det};
        v2 nYAxis = {-XAxis.y / Det, XAxis.x / Det};
        // 计算每个颜色通道的反255值，用于将颜色值从0-255范围转换为0-1范围
        real32 Inv255 = 1.0f / 255.0f;
        __m128 Inv255_4x = _mm_set1_ps(Inv255);
        // 计算每个颜色通道的255倍数，用于将颜色值从0-1范围转换回0-255范围
        real32 One255 = 255.0f;
        __m128 One255_4x = _mm_set1_ps(One255);
        (void)One255_4x;

        __m128 One = _mm_set1_ps(1.0f);
        __m128 Half = _mm_set1_ps(0.5f);
        __m128 Four_4x = _mm_set1_ps(4.0f);
        __m128 Zero = _mm_set1_ps(0.0f);
        __m128i MaskFF = _mm_set1_epi32(0xFF);
        __m128i MaskFFFF = _mm_set1_epi32(0xFFFF);
        __m128i MaskFF00FF = _mm_set1_epi32(0x00FF00FF);
        __m128 Colorr_4x = _mm_set1_ps(Color.r);
        __m128 Colorg_4x = _mm_set1_ps(Color.g);
        __m128 Colorb_4x = _mm_set1_ps(Color.b);
        __m128 Colora_4x = _mm_set1_ps(Color.a);
        __m128 nXAxisx_4x = _mm_set1_ps(nXAxis.x);
        __m128 nXAxisy_4x = _mm_set1_ps(nXAxis.y);
        __m128 nYAxisx_4x = _mm_set1_ps(nYAxis.x);
        __m128 nYAxisy_4x = _mm_set1_ps(nYAxis.y);
        __m128 Originx_4x = _mm_set1_ps(Origin.x);
        __m128 Originy_4x = _mm_set1_ps(Origin.y);

        __m128 WidthM2 = _mm_set1_ps((real32)(Texture->Width - 2));
        __m128 HeightM2 = _mm_set1_ps((real32)(Texture->Height - 2));

        // 计算起始行的位置，用于将数据写入缓冲区
        uint8 *Row =
            ((uint8 *)Buffer->Memory + XMin * BITMAP_BYTES_PER_PIEXLE + YMin * Buffer->Pitch);
        int32 RowAdvance = Buffer->Pitch;

        // TIMED_BLOCK("Pixel_Fill", GetClampedRectArea(FillRect) / 2);
        int32 TexturePitch = Texture->Pitch;
        __m128i TexturePith_4x = _mm_set1_epi32(TexturePitch);
        void *TextureMemory = Texture->Memory;
        // 遍历矩形区域的每一行（从MinY到MaxY）
        for (int Y = YMin; Y < YMax; ++Y) {
            // 当前行的起始地址，Pixel是指向当前行的像素数据指针
            uint32 *Pixel = (uint32 *)Row;
            __m128 PixelPy = _mm_set1_ps((real32)Y);
            PixelPy = _mm_sub_ps(PixelPy, Originy_4x);
            __m128 Pynx = _mm_mul_ps(PixelPy, nXAxisy_4x);
            __m128 Pyny = _mm_mul_ps(PixelPy, nYAxisy_4x);

            __m128 PixelPx = _mm_set_ps((real32)(XMin + 3),  //
                                        (real32)(XMin + 2),  //
                                        (real32)(XMin + 1),  //
                                        (real32)(XMin + 0));
            PixelPx = _mm_sub_ps(PixelPx, Originx_4x);
#define mmSquare(a) _mm_mul_ps(a, a)

            __m128i ClipMask = StartClipMask;
            // 遍历当前行的每一个像素（从MinX到MaxX）
            for (int XI = XMin; XI < XMax; XI += 4) {
#if COUNT_CYCLES
                // clang-format off
counts Counts = {};
#undef _mm_set1_ps
#define _mm_set1_ps(a) ++Counts.mm_set1_ps;a
#define _mm_add_ps(a,b) ++Counts.mm_add_ps;a;b
#define _mm_sub_ps(a,b) ++Counts.mm_sub_ps;a;b
#define _mm_mul_ps(a,b) ++Counts.mm_mul_ps;a;b
#define _mm_castps_si128(a) ++Counts.mm_castps_si128;a
#define _mm_and_ps(a,b) ++Counts.mm_and_ps;a;b
#define _mm_or_ps(a,b) ++Counts.mm_or_ps;a;b
#define _mm_or_si128(a,b) ++Counts.mm_or_si128;a;b
#define _mm_cmpge_ps(a,b) ++Counts.mm_cmpge_ps;a;b
#define _mm_cmple_ps(a,b) ++Counts.mm_cmple_ps;a;b
#define _mm_min_ps(a,b) ++Counts.mm_min_ps;a;b
#define _mm_max_ps(a,b) ++Counts.mm_max_ps;a;b
#define _mm_cvttps_epi32(a) ++Counts.mm_cvttps_epi32;a
#define _mm_cvtps_epi32(a) ++Counts.mm_cvtps_epi32;a
#define _mm_cvtepi32_ps(a) ++Counts.mm_cvtepi32_ps;a
#define _mm_and_si128(a,b) ++Counts.mm_and_si128;a;b
#define _mm_andnot_si128(a,b) ++Counts.mm_andnot_si128;a;b
#define _mm_srli_epi32(a,b) ++Counts.mm_srli_epi32;a;b
#define _mm_slli_epi32(a,b) ++Counts.mm_slli_epi32;a;b
#define _mm_sqrt_ps(a) ++Counts.mm_sqrt_ps;a
#define _mm_movemask_epi8(a) ++Counts.mm_movemask_epi8;a
#define _mm_unpacklo_epi32(a,b) ++Counts.mm_unpacklo_epi32;a;b
#define _mm_unpackhi_epi32(a,b) ++Counts.mm_unpackhi_epi32;a;b

#undef mmSquare
#define mmSquare(a) ++Counts.mm_mul_ps; a
#define __m128 int
#define __m128i int

#define _mm_loadu_si128(a) 0
#define _mm_storeu_si128(a,b)
#endif
                // clang-format on
                __m128 fx = _mm_set1_ps(0.0f);
                __m128 fy = _mm_set1_ps(0.0f);

                __m128 Blendedr = _mm_set1_ps(0.0f);
                __m128 Blendedg = _mm_set1_ps(0.0f);
                __m128 Blendedb = _mm_set1_ps(0.0f);
                __m128 Blendeda = _mm_set1_ps(0.0f);
                IACA_VC64_START;
                // 计算U和V坐标，它们代表了在纹理中的位置，基于d和X轴、Y轴的内积
                __m128 U = _mm_add_ps(_mm_mul_ps(PixelPx, nXAxisx_4x), Pynx);
                // U坐标，基于d和X轴的内积，乘以反向X轴的长度平方
                __m128 V = _mm_add_ps(_mm_mul_ps(PixelPx, nYAxisx_4x), Pyny);
                // V坐标，基于d和Y轴的内积，乘以反向Y轴的长度平方
                __m128i OriginalDest = _mm_load_si128((__m128i *)Pixel);
                __m128i WriteMask = _mm_castps_si128(_mm_and_ps(  //
                    _mm_and_ps(                                   //
                        _mm_cmpge_ps(U, Zero),                    //
                        _mm_cmple_ps(U, One)),                    //
                    _mm_and_ps(                                   //
                        _mm_cmpge_ps(V, Zero),                    //
                        _mm_cmple_ps(V, One))));

                WriteMask = _mm_and_si128(WriteMask, ClipMask);
                // if (_mm_movemask_epi8(WriteMask))
                {
                    U = _mm_min_ps(_mm_max_ps(U, Zero), One);
                    V = _mm_min_ps(_mm_max_ps(V, Zero), One);

                    // 根据U和V计算纹理坐标，tx和ty是浮动的坐标值
                    __m128 tx = _mm_add_ps(_mm_mul_ps(U, WidthM2), Half);   // 计算纹理X坐标
                    __m128 ty = _mm_add_ps(_mm_mul_ps(V, HeightM2), Half);  // 计算纹理Y坐标

                    __m128i FetchX_4x = _mm_cvttps_epi32(tx);
                    __m128i FetchY_4x = _mm_cvttps_epi32(ty);

                    fx = _mm_sub_ps(tx, _mm_cvtepi32_ps(FetchX_4x));
                    fy = _mm_sub_ps(ty, _mm_cvtepi32_ps(FetchY_4x));

                    FetchX_4x = _mm_slli_epi32(FetchX_4x, 2);
                    FetchY_4x = _mm_or_si128(
                        _mm_mullo_epi16(FetchY_4x, TexturePith_4x),  //
                        _mm_slli_epi32(_mm_mulhi_epi16(FetchY_4x, TexturePith_4x), 16));

                    __m128i Fetch_4x = _mm_add_epi32(FetchX_4x, FetchY_4x);

                    int32 Fetch0 = Mi(Fetch_4x, 0);  // 获取纹理的Y坐标整数部分
                    int32 Fetch1 = Mi(Fetch_4x, 1);  // 获取纹理的Y坐标整数部分
                    int32 Fetch2 = Mi(Fetch_4x, 2);  // 获取纹理的Y坐标整数部分
                    int32 Fetch3 = Mi(Fetch_4x, 3);  // 获取纹理的Y坐标整数部分

                    // 获取纹理内存中的起始地址并计算Texel的指针
                    uint8 *TexelPtr0 = ((uint8 *)TextureMemory) + Fetch0;  // 计算x位置偏移

                    // 获取纹理内存中的起始地址并计算Texel的指针
                    uint8 *TexelPtr1 = ((uint8 *)TextureMemory) + Fetch1;  // 计算x位置偏移
                    // 获取纹理内存中的起始地址并计算Texel的指针
                    uint8 *TexelPtr2 = ((uint8 *)TextureMemory) + Fetch2;  // 计算x位置偏移

                    // 获取纹理内存中的起始地址并计算Texel的指针
                    uint8 *TexelPtr3 = ((uint8 *)TextureMemory) + Fetch3;  // 计算x位置偏移

                    __m128i SampleA = _mm_setr_epi32(*(uint32 *)TexelPtr0,  //
                                                     *(uint32 *)TexelPtr1,  //
                                                     *(uint32 *)TexelPtr2,  //
                                                     *(uint32 *)TexelPtr3);

                    __m128i SampleB = _mm_setr_epi32(*(uint32 *)(TexelPtr0 + sizeof(uint32)),
                                                     *(uint32 *)(TexelPtr1 + sizeof(uint32)),
                                                     *(uint32 *)(TexelPtr2 + sizeof(uint32)),
                                                     *(uint32 *)(TexelPtr3 + sizeof(uint32)));

                    __m128i SampleC = _mm_setr_epi32(*(uint32 *)(TexelPtr0 + Texture->Pitch),
                                                     *(uint32 *)(TexelPtr1 + Texture->Pitch),
                                                     *(uint32 *)(TexelPtr2 + Texture->Pitch),
                                                     *(uint32 *)(TexelPtr3 + Texture->Pitch));

                    __m128i SampleD =
                        _mm_setr_epi32(*(uint32 *)(TexelPtr0 + Texture->Pitch + sizeof(uint32)),
                                       *(uint32 *)(TexelPtr1 + Texture->Pitch + sizeof(uint32)),
                                       *(uint32 *)(TexelPtr2 + Texture->Pitch + sizeof(uint32)),
                                       *(uint32 *)(TexelPtr3 + Texture->Pitch + sizeof(uint32)));

#if 1
                    // 解包 TexelSample 中的四个颜色值 (A, B, C, D) 为线性颜色值
                    // SampleA = _mm_set_epi32(0x00000001, 0x00000004, 0x00000010, 0x00000020);
                    __m128i TexelArb = _mm_and_si128(SampleA, MaskFF00FF);
                    __m128i TexelAag = _mm_and_si128(_mm_srli_epi32(SampleA, 8), MaskFF00FF);
                    TexelArb = _mm_mullo_epi16(TexelArb, TexelArb);
                    __m128 TexelAa = _mm_cvtepi32_ps(_mm_srli_epi32(TexelAag, 16));
                    TexelAag = _mm_mullo_epi16(TexelAag, TexelAag);

                    __m128i TexelBrb = _mm_and_si128(SampleB, MaskFF00FF);
                    __m128i TexelBag = _mm_and_si128(_mm_srli_epi32(SampleB, 8), MaskFF00FF);
                    TexelBrb = _mm_mullo_epi16(TexelBrb, TexelBrb);
                    __m128 TexelBa = _mm_cvtepi32_ps(_mm_srli_epi32(TexelBag, 16));
                    TexelBag = _mm_mullo_epi16(TexelBag, TexelBag);

                    __m128i TexelCrb = _mm_and_si128(SampleC, MaskFF00FF);
                    __m128i TexelCag = _mm_and_si128(_mm_srli_epi32(SampleC, 8), MaskFF00FF);
                    TexelCrb = _mm_mullo_epi16(TexelCrb, TexelCrb);
                    __m128 TexelCa = _mm_cvtepi32_ps(_mm_srli_epi32(TexelCag, 16));
                    TexelCag = _mm_mullo_epi16(TexelCag, TexelCag);

                    __m128i TexelDrb = _mm_and_si128(SampleD, MaskFF00FF);
                    __m128i TexelDag = _mm_and_si128(_mm_srli_epi32(SampleD, 8), MaskFF00FF);
                    TexelDrb = _mm_mullo_epi16(TexelDrb, TexelDrb);
                    __m128 TexelDa = _mm_cvtepi32_ps(_mm_srli_epi32(TexelDag, 16));
                    TexelDag = _mm_mullo_epi16(TexelDag, TexelDag);

                    __m128 Destr =
                        _mm_cvtepi32_ps(_mm_and_si128(_mm_srli_epi32(OriginalDest, 16), MaskFF));
                    __m128 Destg =
                        _mm_cvtepi32_ps(_mm_and_si128(_mm_srli_epi32(OriginalDest, 8), MaskFF));
                    __m128 Destb = _mm_cvtepi32_ps(_mm_and_si128(OriginalDest, MaskFF));
                    __m128 Desta =
                        _mm_cvtepi32_ps(_mm_and_si128(_mm_srli_epi32(OriginalDest, 24), MaskFF));

                    // 将每个颜色通道从sRGB空间转换为线性空间，并进行平方运算
                    // 由于sRGB到线性空间的转换是平方，所以使用Square函数处理每个颜色通道

                    __m128 TexelAr = _mm_cvtepi32_ps(_mm_srli_epi32(TexelArb, 16));
                    __m128 TexelAg = _mm_cvtepi32_ps(_mm_and_si128(TexelAag, MaskFFFF));
                    __m128 TexelAb = _mm_cvtepi32_ps(_mm_and_si128(TexelArb, MaskFFFF));

                    __m128 TexelBr = _mm_cvtepi32_ps(_mm_srli_epi32(TexelBrb, 16));
                    __m128 TexelBg = _mm_cvtepi32_ps(_mm_and_si128(TexelBag, MaskFFFF));
                    __m128 TexelBb = _mm_cvtepi32_ps(_mm_and_si128(TexelBrb, MaskFFFF));

                    __m128 TexelCr = _mm_cvtepi32_ps(_mm_srli_epi32(TexelCrb, 16));
                    __m128 TexelCg = _mm_cvtepi32_ps(_mm_and_si128(TexelCag, MaskFFFF));
                    __m128 TexelCb = _mm_cvtepi32_ps(_mm_and_si128(TexelCrb, MaskFFFF));

                    __m128 TexelDr = _mm_cvtepi32_ps(_mm_srli_epi32(TexelDrb, 16));
                    __m128 TexelDg = _mm_cvtepi32_ps(_mm_and_si128(TexelDag, MaskFFFF));
                    __m128 TexelDb = _mm_cvtepi32_ps(_mm_and_si128(TexelDrb, MaskFFFF));

                    // 进行线性插值：首先根据 fx 在 TexelA 和 TexelB 之间进行插值，
                    // 然后根据 fx 在 TexelC 和 TexelD 之间进行插值，得到两组插值结果
                    // 最后根据 fy 在两组插值结果之间进行插值
                    __m128 ifx = _mm_sub_ps(One, fx);
                    __m128 ify = _mm_sub_ps(One, fy);
                    __m128 l0 = _mm_mul_ps(ify, ifx);
                    __m128 l1 = _mm_mul_ps(ify, fx);
                    __m128 l2 = _mm_mul_ps(fy, ifx);
                    __m128 l3 = _mm_mul_ps(fy, fx);
                    __m128 Texelr = _mm_add_ps(        //
                        _mm_add_ps(                    //
                            _mm_mul_ps(l0, TexelAr),   //
                            _mm_mul_ps(l1, TexelBr)),  //
                        _mm_add_ps(                    //
                            _mm_mul_ps(l2, TexelCr),   //
                            _mm_mul_ps(l3, TexelDr)));
                    __m128 Texelg = _mm_add_ps(        //
                        _mm_add_ps(                    //
                            _mm_mul_ps(l0, TexelAg),   //
                            _mm_mul_ps(l1, TexelBg)),  //
                        _mm_add_ps(                    //
                            _mm_mul_ps(l2, TexelCg),   //
                            _mm_mul_ps(l3, TexelDg)));
                    __m128 Texelb = _mm_add_ps(        //
                        _mm_add_ps(                    //
                            _mm_mul_ps(l0, TexelAb),   //
                            _mm_mul_ps(l1, TexelBb)),  //
                        _mm_add_ps(                    //
                            _mm_mul_ps(l2, TexelCb),   //
                            _mm_mul_ps(l3, TexelDb)));
                    __m128 Texela = _mm_add_ps(        //
                        _mm_add_ps(                    //
                            _mm_mul_ps(l0, TexelAa),   //
                            _mm_mul_ps(l1, TexelBa)),  //
                        _mm_add_ps(                    //
                            _mm_mul_ps(l2, TexelCa),   //
                            _mm_mul_ps(l3, TexelDa)));

                    // 对纹理颜色进行颜色分量逐项相乘，调整亮度
                    Texelr = _mm_mul_ps(Texelr, Colorr_4x);
                    Texelg = _mm_mul_ps(Texelg, Colorg_4x);
                    Texelb = _mm_mul_ps(Texelb, Colorb_4x);
                    Texela = _mm_mul_ps(Texela, Colora_4x);

                    __m128 MaxColorValue = _mm_set1_ps(255.0f * 255.0f);
                    Texelr = _mm_min_ps(_mm_max_ps(Texelr, Zero), MaxColorValue);
                    // 限制红色通道的值
                    Texelg = _mm_min_ps(_mm_max_ps(Texelg, Zero), MaxColorValue);
                    // 限制绿色通道的值
                    Texelb = _mm_min_ps(_mm_max_ps(Texelb, Zero), MaxColorValue);
                    // 限制蓝色通道的值

                    // 将每个颜色通道从sRGB空间转换为线性空间，并进行平方运算
                    // 由于sRGB到线性空间的转换是平方，所以使用Square函数处理每个颜色通道
                    Destr = mmSquare(Destr);  // 红色通道
                    Destg = mmSquare(Destg);  // 绿色通道
                    Destb = mmSquare(Destb);  // 蓝色通道
                    // Alpha通道只是按比例缩放，保持线性

                    __m128 InvTexelA = _mm_sub_ps(One, _mm_mul_ps(Inv255_4x, Texela));
                    Blendedr = _mm_add_ps(_mm_mul_ps(InvTexelA, Destr), Texelr);
                    Blendedg = _mm_add_ps(_mm_mul_ps(InvTexelA, Destg), Texelg);
                    Blendedb = _mm_add_ps(_mm_mul_ps(InvTexelA, Destb), Texelb);
                    Blendeda = _mm_add_ps(_mm_mul_ps(InvTexelA, Desta), Texela);

                    // 注意：从线性亮度空间到sRGB转换

                    // 将每个颜色通道从线性空间转换回sRGB空间，并进行平方根运算
                    // 由于线性空间到sRGB的转换是平方根，所以使用SquareRoot函数处理每个颜色通道
#if 0
                Blendedr = _mm_mul_ps(Blendedr, _mm_rsqrt_ps(Blendedr));  // 红色通道
                Blendedg = _mm_mul_ps(Blendedg, _mm_rsqrt_ps(Blendedg));  // 绿色通道
                Blendedb = _mm_mul_ps(Blendedb, _mm_rsqrt_ps(Blendedb));  // 蓝色通道
#else

                    Blendedr = _mm_sqrt_ps(Blendedr);  // 红色通道
                    Blendedg = _mm_sqrt_ps(Blendedg);  // 绿色通道
                    Blendedb = _mm_sqrt_ps(Blendedb);  // 蓝色通道
#endif

                    // uint32 Rs[] = {0x00000050, 0x00000051, 0x00000052, 0x00000053};
                    // uint32 Gs[] = {0x000000C0, 0x000000C1, 0x000000C2, 0x000000C3};
                    // uint32 Bs[] = {0x000000B0, 0x000000B1, 0x000000B2, 0x000000B3};
                    // uint32 As[] = {0x000000A0, 0x000000A1, 0x000000A2, 0x000000A3};
                    // __m128i Intr = *(__m128i *)Rs;
                    // __m128i Intg = *(__m128i *)Gs;
                    // __m128i Intb = *(__m128i *)Bs;
                    // __m128i Inta = *(__m128i *)As;

                    __m128i Intr = _mm_cvtps_epi32(Blendedr);
                    __m128i Intg = _mm_cvtps_epi32(Blendedg);
                    __m128i Intb = _mm_cvtps_epi32(Blendedb);
                    __m128i Inta = _mm_cvtps_epi32(Blendeda);
                    __m128i Sr = _mm_slli_epi32(Intr, 16);
                    __m128i Sg = _mm_slli_epi32(Intg, 8);
                    __m128i Sb = Intb;
                    __m128i Sa = _mm_slli_epi32(Inta, 24);
                    __m128i Out = _mm_or_si128(_mm_or_si128(Sr, Sg),  //
                                               _mm_or_si128(Sb, Sa));
#else
                    __m128i Out = _mm_or_si128(FetchX_4x,  //
                                               FetchY_4x);

#endif

                    __m128i MaskOut = _mm_or_si128(_mm_and_si128(WriteMask, Out),  //
                                                   _mm_andnot_si128(WriteMask, OriginalDest));

#if 0
                __m128i R1B1R0B0 =
                    _mm_unpacklo_epi32(_mm_castps_si128(Blendedb), _mm_castps_si128(Blendedr));
                __m128i A1G1A0G0 =
                    _mm_unpacklo_epi32(_mm_castps_si128(Blendedg), _mm_castps_si128(Blendeda));
                __m128i R3B3R2B2 =
                    _mm_unpackhi_epi32(_mm_castps_si128(Blendedb), _mm_castps_si128(Blendedr));
                __m128i A3G3A2G2 =
                    _mm_unpackhi_epi32(_mm_castps_si128(Blendedg), _mm_castps_si128(Blendeda));

                __m128i ARGB0 = _mm_unpacklo_epi32(R1B1R0B0, A1G1A0G0);
                __m128i ARGB1 = _mm_unpackhi_epi32(R1B1R0B0, A1G1A0G0);
                __m128i ARGB2 = _mm_unpacklo_epi32(R3B3R2B2, A3G3A2G2);
                __m128i ARGB3 = _mm_unpackhi_epi32(R3B3R2B2, A3G3A2G2);
                (void)ARGB0;
                (void)ARGB1;
                (void)ARGB2;
                (void)ARGB3;
                (void)MaskOut;
#endif

                    // *(__m128i *)Pixel = Out;
                    _mm_store_si128((__m128i *)Pixel, MaskOut);
                }
#if COUNT_CYCLES
#undef _mm_add_ps
                real32 Third = 1.0f / 3.0f;
                real32 Total = 0.0f;
#define Sum(L, A)    \
    (L * (real32)A); \
    Total += (L * (real32)A);
                real32 mm_set1_ps = Sum(0.0f, Counts.mm_set1_ps);
                real32 mm_add_ps = Sum(0.5f, Counts.mm_add_ps);
                real32 mm_sub_ps = Sum(0.5f, Counts.mm_sub_ps);
                real32 mm_mul_ps = Sum(0.5f, Counts.mm_mul_ps);
                real32 mm_castps_si128 = Sum(0.0f, Counts.mm_castps_si128);
                real32 mm_and_ps = Sum(Third, Counts.mm_and_ps);
                real32 mm_or_ps = Sum(Third, Counts.mm_or_ps);
                real32 mm_or_si128 = Sum(Third, Counts.mm_or_si128);
                real32 mm_cmpge_ps = Sum(0.5f, Counts.mm_cmpge_ps);
                real32 mm_cmple_ps = Sum(0.5f, Counts.mm_cmple_ps);
                real32 mm_min_ps = Sum(0.5f, Counts.mm_min_ps);
                real32 mm_max_ps = Sum(0.5f, Counts.mm_max_ps);
                real32 mm_cvttps_epi32 = Sum(0.5f, Counts.mm_cvttps_epi32);
                real32 mm_cvtps_epi32 = Sum(0.5f, Counts.mm_cvtps_epi32);
                real32 mm_cvtepi32_ps = Sum(0.5f, Counts.mm_cvtepi32_ps);
                real32 mm_and_si128 = Sum(Third, Counts.mm_and_si128);
                real32 mm_andnot_si128 = Sum(Third, Counts.mm_andnot_si128);
                real32 mm_srli_epi32 = Sum(0.5f, Counts.mm_srli_epi32);
                real32 mm_slli_epi32 = Sum(0.5f, Counts.mm_slli_epi32);
                real32 mm_sqrt_ps = Sum(3.0f, Counts.mm_sqrt_ps);
                real32 mm_movemask_epi8 = Sum(1.0f, Counts.mm_movemask_epi8);
                real32 mm_unpackhi_epi32 = Sum(0.5f, Counts.mm_unpackhi_epi32);
                real32 mm_unpacklo_epi32 = Sum(0.5f, Counts.mm_unpacklo_epi32);
                (void)mm_set1_ps;
                (void)mm_add_ps;
                (void)mm_sub_ps;
                (void)mm_mul_ps;
                (void)mm_castps_si128;
                (void)mm_and_ps;
                (void)mm_or_ps;
                (void)mm_or_si128;
                (void)mm_cmpge_ps;
                (void)mm_cmple_ps;
                (void)mm_min_ps;
                (void)mm_max_ps;
                (void)mm_cvttps_epi32;
                (void)mm_cvtps_epi32;
                (void)mm_cvtepi32_ps;
                (void)mm_and_si128;
                (void)mm_andnot_si128;
                (void)mm_srli_epi32;
                (void)mm_slli_epi32;
                (void)mm_sqrt_ps;
                (void)mm_movemask_epi8;
                (void)mm_unpackhi_epi32;
                (void)mm_unpacklo_epi32;
#endif
                PixelPx = _mm_add_ps(PixelPx, Four_4x);
                Pixel += 4;
                if ((XI + 8) < XMax) {
                    ClipMask = _mm_set1_epi8(-1);
                } else {
                    ClipMask = EndClipMask;
                }
                IACA_VC64_END;
            }
            // 跳到下一行的起始地址
            Row += RowAdvance;  // 根据图像的每行的字节数跳到下一行
        }
    }
}

render_entry_cliprect *LinearizeClipRects(game_render_commands *Commands, memory_arena *TempArena) {
    render_entry_cliprect *Result =
        PushArray(TempArena, Commands->ClipRectCount, render_entry_cliprect);

    render_entry_cliprect *Out = Result;
    for (render_entry_cliprect *Rect = Commands->FirstRect; Rect; Rect = Rect->Next) {
        *Out++ = *Rect;
    }
    return Result;
}

game_render_prep PrepForRender(game_render_commands *Commands, memory_arena *TempArena) {
    game_render_prep Prep;
    SortEntries(Commands, TempArena, &Prep);
    Prep.ClipRects = LinearizeClipRects(Commands, TempArena);
    return Prep;
}

rectangle2i AspectRatioFit(uint32 RenderWidth, uint32 RenderHeight,  //
                           uint32 WindowWidth, uint32 WindowHeight) {
    rectangle2i Result = {};
    if ((RenderWidth > 0) && (RenderHeight > 0) && (WindowWidth > 0) && (WindowHeight > 0)) {
        real32 OptimalWindowWith =
            (real32)WindowHeight * ((real32)RenderWidth / (real32)RenderHeight);
        real32 OptimalWindowHeight =
            (real32)WindowWidth * ((real32)RenderHeight / (real32)RenderWidth);
        if (OptimalWindowWith > (real32)WindowWidth) {
            Result.MinX = 0;
            Result.MaxX = WindowWidth;
            real32 Empty = (real32)WindowHeight - OptimalWindowHeight;
            int32 HalfEmpty = RoundReal32ToInt32(0.5f * Empty);
            int32 UseHeight = RoundReal32ToInt32(OptimalWindowHeight);
            Result.MinY = HalfEmpty;
            Result.MaxY = Result.MinY + UseHeight;
        } else {
            Result.MinY = 0;
            Result.MaxY = WindowHeight;
            real32 Empty = (real32)WindowWidth - OptimalWindowWith;
            int32 HalfEmpty = RoundReal32ToInt32(0.5f * Empty);
            int32 UseWidth = RoundReal32ToInt32(OptimalWindowWith);

            Result.MinX = HalfEmpty;
            Result.MaxX = Result.MinX + UseWidth;
        }
    }
    return Result;
}